package com.ramos.kuaixiao.db;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;

import com.ramos.kuaixiao.entity.EmpStoreHouse;
import com.ramos.kuaixiao.entity.WareHouse;
import com.ramos.kuaixiao.utils.SharedPreference;
import com.ramos.kuaixiao.utils.StringUtil;

import java.util.ArrayList;
import java.util.List;

public class EmpStoreHouseDB {
    private static String TAG = "EmpStoreHouseDB";
    private static String TABLE_NAME = "EmpStoreHouse";
    public static final String CREATE_TABLE_SQL;
    public static final String DROP_USERINFO;

    static {
        CREATE_TABLE_SQL = "CREATE TABLE " + TABLE_NAME + " (" + "did" + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
                + "dealer_id" + " CHAR(30)," + "employer_id" + " CHAR(30)," + "storehouse_list" + " CHAR(30),"+ "modifyTime" + " Long);";
        DROP_USERINFO = "DROP TABLE IF EXISTS " + TABLE_NAME;
    }

    public int addAllCustomer(List<EmpStoreHouse> customer) {
        SQLiteDatabase db = DBHelper.open();
        db.execSQL("DELETE FROM EmpStoreHouse");
        String sql = "insert into EmpStoreHouse(dealer_id,employer_id,storehouse_list, modifyTime) values(?,?,?,?)";
        db.beginTransaction();
        Long a = System.currentTimeMillis();
        SQLiteStatement stmt = db.compileStatement(sql);
        for (int i = 0; i < customer.size(); i++) {
            stmt.bindString(1, customer.get(i).getDealerId() + "");
            stmt.bindString(2, customer.get(i).getEmpId() + "");
            stmt.bindString(3, customer.get(i).getStorehouseList() + "");
            stmt.bindString(4, customer.get(i).getModifyTime() + "");
            stmt.execute();
            stmt.clearBindings();
        }
        db.setTransactionSuccessful();
        db.endTransaction();
        Long b = System.currentTimeMillis();
        Log.i(TAG, String.valueOf(b - a));
        return 0;
    }

    public int updateAllEmpStoreHouse(List<EmpStoreHouse> customer) {
        SQLiteDatabase db = DBHelper.open();
        db.beginTransaction();
        Long a = System.currentTimeMillis();
        Log.d(TAG, "updateAllEmpStoreHouse:"+customer.size());
        for (int i = 0; i < customer.size(); i++) {
            Log.d(TAG, customer.get(i).getDealerId() + " " +  customer.get(i).getEmpId()+ " " +  customer.get(i).getStorehouseList());
            EmpStoreHouse firstWarehouse = customer.get(i);
            if(hasEmpBrand(firstWarehouse.getEmpId()+"")){
                ContentValues cv = new ContentValues();
                cv.put("storehouse_list", firstWarehouse.getStorehouseList() + "");
                cv.put("modifyTime", firstWarehouse.getModifyTime() + "");
                int j = db.update("EmpStoreHouse",cv,"employer_id=?", new String[]{firstWarehouse.getEmpId() + ""}) ; //如果有记录，则更新，并返回1，否则返回0*//*

                Log.d(TAG, j + ":j");

            } else{
                ContentValues cv = new ContentValues();
                cv.put("dealer_id", firstWarehouse.getDealerId() + "");
                cv.put("employer_id", firstWarehouse.getEmpId() + "");
                cv.put("storehouse_list", firstWarehouse.getStorehouseList() + "");
                cv.put("modifyTime", firstWarehouse.getModifyTime() + "");
                db.insert("EmpStoreHouse",null, cv) ; //如果有记录，则更新，并返回1，否则返回0
            }
            // 生成的sql是 INSERT INTRO OR REPLACE INTO 这样的 (如果存在就替换存在的字段值. 存在的判断标准是主键冲突, 这里的主键是userId). 下面会介绍这个地方的方法
            //db.insertWithOnConflict("StoreNum",null, cv, SQLiteDatabase.CONFLICT_REPLACE) ; //如果有记录，则更新，并返回1，否则返回0
        }
        db.setTransactionSuccessful();
        db.endTransaction();
        Long b = System.currentTimeMillis();
        Log.i(TAG, String.valueOf(b - a));
        //updateStoreHouse();
        return 0;
    }

    private void updateStoreHouse() {
        String houseList = "";
        List<WareHouse> tmpList = new ArrayList<>();
        List<WareHouse> list = new WareHouseDB().findAllWareHouse(SharedPreference.getPreferString("org"));
        Log.d(TAG, "tbl_WareHouse:" + list.size());
        for(WareHouse wareHouse : list){
            Log.d(TAG, "wareHouse:" + wareHouse.getName());
        }
        List<EmpStoreHouse> list1 = new EmpStoreHouseDB().findAllCustomer();

        if (list1.size() > 0 && list.size() > 0) {
            for (EmpStoreHouse empStoreHouse : list1) {
                if (empStoreHouse.getEmpId().equals(SharedPreference.getPreferString("id"))) {
                    houseList = empStoreHouse.getStorehouseList();
                }
            }
            Log.d(TAG, "houseList:" + houseList);
            if (!StringUtil.isEmpty(houseList)) {
                String[] list2 = houseList.split("_");
                if (list2.length > 0) {
                    for (String s : list2) {
                        for (WareHouse wareHouse : list) {
                            if (s.equals(wareHouse.getId())) {
                                tmpList.add(wareHouse);

                            }
                        }
                    }
                }

            } else {
                tmpList.addAll(list);
            }
            Log.d(TAG, "tmpList:" + list.size());
            WareHouseDB shopsDB = new WareHouseDB();
            shopsDB.addAllWareHouse(tmpList);
        }
    }


    private boolean hasEmpBrand(String s) {
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select * from EmpStoreHouse where employer_id =? ", new String[]{s});
        if (cursor.getCount() > 0) {
            cursor.close();
            Log.d(TAG, "EmpStoreHouse true");
            return true;
        } else {
            Log.d(TAG, "EmpStoreHouse false");
            cursor.close();
            return false;
        }
    }

    public List<EmpStoreHouse> findAllCustomer() {
        List<EmpStoreHouse> list = new ArrayList<>();
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select * from EmpStoreHouse", new String[]{});
        Log.d(TAG, "cursor:" + cursor.getCount());
       /* for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToNext();

        }*/

        while(cursor.moveToNext()){
            EmpStoreHouse customer = new EmpStoreHouse();
            customer.setDealerId(cursor.getString(1));
            customer.setEmpId(cursor.getString(2));
            customer.setStorehouseList(cursor.getString(3));
            list.add(customer);
            Log.d(TAG, "cursor.getString(1):" + cursor.getString(1) + " " + cursor.getString(2) + " " +cursor.getString(3) );
        }
        cursor.close();
        //db.close();
        //Log.d(TAG, "findAllCustomer:" + list.size());
        return list;
    }

    public long getMaxModifyTime() {
        long param = 0;
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select max(modifyTime)from EmpStoreHouse ", new String[]{});
        Log.d(TAG, "getMaxModifyTime:getCount" + cursor.getCount());
        if (cursor.moveToFirst()) {

            param = cursor.getLong(0);
        }
        cursor.close();
        Log.d(TAG, "getMaxModifyTime:param" + param);
        return param;
    }

    public void deleteAll() {
        SQLiteDatabase db = DBHelper.open();
        db.execSQL("DELETE FROM EmpStoreHouse");
        Log.d(TAG, "deleteAllEmpStoreHouse ");
    }

    public boolean hasData() {
        SQLiteDatabase db = DBHelper.open();
        Cursor cursor = db.rawQuery("select count(*)from EmpStoreHouse", null);
        cursor.moveToFirst();
        Long count = cursor.getLong(0);
        if (count > 0) {
            cursor.close();
            Log.d(TAG, "SaleCustomer true");
            return true;
        } else {
            Log.d(TAG, "SaleCustomer false");
            cursor.close();
            return false;
        }
    }

}
